<template>
  <div class="xd-contract">
      <div class="list" v-show="isShow">
        <Card>
          <p slot="title">
            <Icon type="md-list" />
            合同列表
          </p>
          <Form ref="formInline" :model="formSearch"  inline>
              <FormItem prop="depaid" v-show="this.access!=='wash'">
                <Select class="select" v-model="formSearch.depaid" placeholder="请选择洗涤公司">
                  <Option v-for="item in washList" :value="item.depaid" :key="item.depaid">
                  {{ item.depaname }}
                  </Option>
                </Select>
              </FormItem>
              <FormItem prop="name">
                  <Input type="text" v-model="formSearch.name" placeholder="请输入客户名称"></Input>
              </FormItem>
              <FormItem prop="contractname">
                  <Input type="text" v-model="formSearch.contractname" placeholder="请输入合同名称"></Input>
              </FormItem>
              <FormItem>
                  <Button type="primary" @click="handleSeacrh()">查询</Button>
              </FormItem>
               <FormItem>
                  <Button type="primary" @click="handleAdd()" v-show="access=='wash'">新增合同</Button>
              </FormItem>
          </Form>
          <Table highlight-row stripe :columns="columns" :data="data" ></Table>
          <div style="margin: 10px;overflow: hidden">
            <div style="float: right;">
                <Page :total="page.total" :page-size="page.pageSize" :current="1" @on-change="changePage" show-total></Page>
            </div>
          </div>
          <Modal
            v-model="modal"
            footer-hide="true"
            transfer="false"
            >
            <p slot="header">
              <Icon type="ios-paper" />
              <span>查看详情</span>
            </p>
            <p class="viewLine"><span>序号:</span> {{currentData.id}}</p>
            <p class="viewLine"><span>客户名称:</span>{{currentData.customername}}</p>
            <p class="viewLine"><span>合同名称:</span>{{currentData.contractname}}</p>
            <p class="viewLine"><span>生效日期:</span>{{formatTime(currentData.vailddate,true)}}</p>
            <p class="viewLine"><span>终止日期:</span>{{formatTime(currentData.lastdate,true)}}</p>
            <p class="viewLine"><span>状态:</span>{{currentData.state}}</p>
            <p class="viewLine"><span>创建时间:</span>{{formatTime(currentData.creationdate)}}</p>
            <p class="viewLine"><span>更新时间:</span>{{formatTime(currentData.lastdate)}}</p>
            <p class="viewLine"><span>备注:</span>{{currentData.remark}}</p>
            <p class="viewLine"><span>文件:</span>
              <div class="contract-upload-list" v-for="item in uploadList" :key="item.url">
                <img :src="item.url">
                <div class="contract-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                </div>
              </div>
            </p>
          </Modal>
        </Card>
      </div>
      <div class="add" v-show="!isShow">
        <Card>
          <p slot="title">
            <Icon type="ios-create" v-show="this.type!=='edit'"/>
            <Icon type="ios-document" v-show="this.type=='edit'"/>
            {{this.type == "edit" ? "合同编辑" : "合同新增"}}
          </p>
          <p slot="extra" >
            <Button type="primary" @click="goBack()">返回</Button>
          </p>
          <div class="editForm">
            <Form ref="editFormContract" :model="editFormInLine" :rules="editFormRuleInline" :label-width="80">
              <FormItem label="客户名称" prop="name">
                <Input v-model="editFormInLine.name" placeholder="请输入客户名称"></Input>
              </FormItem>
              <FormItem label="合同名称" prop="contractName">
                <Input v-model="editFormInLine.contractName" placeholder="请输入合同名称"></Input>
              </FormItem>
              <FormItem label="生效日期"  prop="contractStartTime">
                <DatePicker type="date" placeholder="请选择生效日期" :options="startTimeOption" v-model="editFormInLine.contractStartTime"  @on-change="onStartTimeChange"></DatePicker>
              </FormItem>
              <FormItem label="终止日期"  prop="contractEndTime">
                <DatePicker type="date" placeholder="请选择终止日期" :options="endTimeOption" v-model="editFormInLine.contractEndTime" @on-change="onEndTimeChange"></DatePicker>
              </FormItem>
              <FormItem label="状态" prop="status">
                <Select class="select" v-model="editFormInLine.status">
                  <Option value="有效">有效</Option>
                  <Option value="无效">无效</Option>
                </Select>
              </FormItem>
              <FormItem label="上传合同">
                <div class="contract-upload-list" v-for="item in uploadList" :key="item.url">
                  <img :src="item.url">
                  <div class="contract-upload-list-cover">
                      <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                      <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                  </div>
                </div>
                <Upload
                  ref="upload"
                  :show-upload-list="false"
                  :on-success="handleSuccess"
                  :format="['jpg','jpeg','png','pdf']"
                  :max-size="10240"
                  :on-error="handleError"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  :before-upload="handleBeforeUpload"
                  multiple
                  type="drag"
                  action="/api/Insert/UploadImg2"
                  style="display: inline-block;width:58px;">
                  <div style="width: 58px;height:58px;line-height: 58px;">
                      <Icon type="ios-camera" size="20"></Icon>
                  </div>
                </Upload>
                <Modal title="查看图片" v-model="visible">
                    <img :src="imgUrl" v-if="visible" style="width: 100%">
                </Modal>
              </FormItem>
              <FormItem label="备注" prop="remark">
                <Input v-model="editFormInLine.remark" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="备注" maxlength="50"></Input>
              </FormItem>
              <FormItem>
                <Button @click="handleSubmit" type="primary" class="button">提交</Button>
                <Button @click="handleReset" type="primary" class="button">重置</Button>
              </FormItem>
            </Form>
          </div>
        </Card>
      </div>
    </Card>
  </div>
</template>

<script>
import API from "./api";
import ValidatorRule from "@/filters/validator-rule";
import { formatArrObjIndex, formatNetTime } from "@/libs/tools";
import i18n from "./locale";
import mixinTag from "@/mixin/tag-mixin";

export default {
  name: "xd-contract",
  components: {},
  mixins: [mixinTag],
  data() {
    return {
      i18n: i18n,
      modal: false,
      isShow: true,
      currentData: "",
      access: "",
      type: "",
      imgUrl: "",
      visible: false,
      uploadList: [],
      washList: [],
      page: {
        total: 0,
        pageSize: 20
      },
      editFormInLine: {
        name: "",
        contractName: "",
        contractStartTime: "",
        contractEndTime: "",
        status: "",
        uploads: "",
        remark: ""
      },
      editFormRuleInline: {
        name: ValidatorRule.company,
        contractName: ValidatorRule.company,
        contractStartTime: ValidatorRule.selectDate,
        contractEndTime: ValidatorRule.selectDate,
        status: ValidatorRule.select,
        uploads: ValidatorRule.require
      },
      startTimeOption: {},
      endTimeOption: {},
      formSearch: {
        depaid: "",
        name: "",
        contractname: "",
        pageNum: 1,
        pageSize: 20
      },
      columns: [
        {
          title: "序号",
          key: "id"
        },
        {
          title: "客户名称",
          key: "customername"
        },
        {
          title: "合同名称",
          key: "contractname"
        },
        {
          title: "生效日期",
          key: "vailddate",
          ellipsis: true,
          tooltip: true,
          render: (h, params) => {
            return h("span", this.formatTime(params.row.vailddate, true));
          }
        },
        {
          title: "终止日期",
          key: "lastdate",
          ellipsis: true,
          tooltip: true,
          render: (h, params) => {
            return h("span", this.formatTime(params.row.lastdate, true));
          }
        },
        {
          title: "状态",
          key: "state"
        },
        {
          title: "操作",
          key: "action",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.show(params.index);
                    }
                  }
                },
                "查看"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.index);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.delete(params.index, params.row.id);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      data: []
    };
  },

  mounted() {
    this.resetInit();
  },

  activated() {
    let userInfo = this.$store.state.user.userInfo.data;
    this.access = this.$store.state.user.access;
    if (this.access !== "wash") {
      this.getWashlList();
    }
  },

  methods: {
    resetInit() {
      let userInfo = this.$store.state.user.userInfo.data;
      this.access = this.$store.state.user.access;
      if (this.access == "wash") {
        this.formSearch.depaid = userInfo.depaid;
        this.handleSeacrh();
      } else {
        this.getWashlList();
      }
    },

    getWashlList() {
      API.getWashlList({ type: 1 })
        .then(res => {
          if (res.code == 200) {
            this.washList = res.data;
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    onStartTimeChange(startTime, type) {
      this.endTimeOption = {
        disabledDate(endTime) {
          return endTime < new Date(startTime);
        }
      };
    },

    onEndTimeChange(endTime, type) {
      this.startTimeOption = {
        disabledDate(startTime) {
          return startTime > new Date(endTime);
        }
      };
    },

    formatTime: function(timeStr1, bool) {
      return formatNetTime(timeStr1, bool);
    },

    handleSeacrh() {
      let obj = this.formSearch;
      obj.pageNum = 1;
      if (obj.depaid == "") {
        this.$Message.error("查询洗涤公司必选！");
        return;
      }
      this.formSearch = obj;
      this.getList(obj);
    },

    changePage(pageNum) {
      let obj = this.formSearch,
        maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      if (obj.pageNum > maxPageNum) {
        obj.pageNum = maxPageNum;
      } else {
        obj.pageNum = pageNum;
      }
      this.formSearch = obj;
      this.getList(obj);
    },

    resetList() {
      //求余为1，页码为最大页码，请求页需减1
      let maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      let remainderNum = this.page.total % this.page.pageSize;
      if (
        this.formSearch.pageNum == maxPageNum &&
        remainderNum == 1 &&
        this.formSearch.pageNum !== 1
      ) {
        this.formSearch.pageNum = this.formSearch.pageNum - 1;
      }
      let obj = this.formSearch;
      this.getList(obj);
    },

    getList(obj) {
      API.getList(obj)
        .then(res => {
          let data = res.data;
          this.page.total = data.total;
          this.page.pageSize = data.pageSize;
          this.data = data.list;
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    handleAdd() {
      this.isShow = false;
      this.type = "add";
      this.currentData = "";
      this.uploadList = [];
      this.handleReset();
    },

    show(index) {
      this.currentData = this.data[index];
      this.assembleUploadedData();
      this.modal = true;
    },

    edit(index) {
      this.isShow = false;
      this.type = "edit";
      this.currentData = this.data[index];
      // 赋值
      this.editFormInLine.name = this.currentData.customername;
      this.editFormInLine.contractName = this.currentData.contractname;
      this.editFormInLine.contractStartTime = this.formatTime(
        this.currentData.vailddate,
        true
      );
      this.editFormInLine.contractEndTime = this.formatTime(
        this.currentData.lastdate,
        true
      );
      this.editFormInLine.status = this.currentData.state;
      this.editFormInLine.uploads = this.currentData.urls;
      this.editFormInLine.remark = this.currentData.remark;
      this.assembleUploadedData();
    },

    assembleUploadedData() {
      let tthis = this,
        arr = this.currentData.urls ? JSON.parse(this.currentData.urls) : [];
      this.uploadList = [];
      _.forEach(arr, function(value) {
        let obj = {
          url: value
        };
        tthis.uploadList.push(obj);
      });
    },

    delete(index, id) {
      let tthis = this;
      this.$Modal.confirm({
        title: "提示：",
        content: "你确定删除这条记录",
        onOk: function() {
          let obj = {
            id: id,
            type: "Contract"
          };
          API.delete(obj)
            .then(res => {
              if (res.code == 200) {
                this.$Message.success({ content: "该记录已经删除成功！" });
                tthis.data.splice(index, 1);
                tthis.resetList();
              }
            })
            .catch(err => {
              this.$Message.error("请求异常！");
            });
        }
      });
    },

    goBack() {
      this.isShow = true;
      this.handleReset();
    },

    handleReset() {
      this.$refs.editFormContract.resetFields();
    },

    handleSubmit() {
      this.editFormInLine = this.addUploadToData(this.editFormInLine);
      this.$refs.editFormContract.validate(valid => {
        if (valid) {
          if (this.type == "edit") {
            this.editSubmit(this.editFormInLine);
          } else {
            this.addSubmit(this.editFormInLine);
          }
        }
      });
    },

    editSubmit(obj) {
      obj.id = this.currentData.id;
      obj.contractEndTime = new Date(obj.contractEndTime); //时间转换
      obj.contractStartTime = new Date(obj.contractEndTime); //时间转换
      API.editSubmit(obj)
        .then(res => {
          this.resetList();
          this.$Message.success("修改成功！");
          this.goBack();
        })
        .catch(err => {
          this.$Message.error("修改异常！");
        });
    },

    addUploadToData(obj) {
      let arr = [];
      for (let i in this.uploadList) {
        arr.push(this.uploadList[i].url);
      }
      if (arr.length > 0) {
        obj.uploads = JSON.stringify(arr);
      } else {
        obj.uploads = "";
      }
      return obj;
    },

    addSubmit(obj) {
      API.addSubmit(obj)
        .then(res => {
          if (res.code == 200) {
            this.handleSeacrh();
            this.$Message.success("添加成功！");
            this.goBack();
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    /***图片相关***/
    handleView(obj) {
      this.imgUrl = obj.url;
      this.visible = true;
    },
    handleError(err, file) {
      console.log("handleError", err);
    },
    handleRemove(file) {
      let index = formatArrObjIndex(this.uploadList, "url", file.url);
      this.uploadList.splice(index, 1);
    },
    handleSuccess(res, file) {
      file.url = file.response.data.url;
      this.uploadList.push(file);
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "文件格式不正确",
        desc: "文件" + file.name + " 的格式不正确, 请选择正确的格式."
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "上传文件大小限制",
        desc: "文件" + file.name + " 太大,不能超过10M."
      });
    },
    handleBeforeUpload(file) {
      const check = this.uploadList.length < 4;
      if (!check) {
        this.$Notice.warning({
          title: "最多上传4张图片."
        });
      }
      return check;
    }
  }
};
</script>
<style lang="less" >
@import "./xd-contract.less";
</style>
